package com.cx.thread;

import java.util.concurrent.*;

public class CallablePool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 最大线程数设置为5，队列最大能存3，使用主线程执行的拒绝策略
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            2, 5, 10, TimeUnit.SECONDS, 
            new ArrayBlockingQueue<Runnable>(3),
            new ThreadPoolExecutor.CallerRunsPolicy()
        );

        int n = 5;
        for (int i = 0; i < 6; i++) {
            // 提交任务
            Future<Integer> result = threadPoolExecutor.submit(new MyCallable(i * 100));
            System.out.println("提交任务：" + i * 100);
        }

        // 关闭线程池
        threadPoolExecutor.shutdown();
        // 等待线程池关闭
        if (!threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS)) {
            System.out.println("线程池未在指定时间内关闭");
        }
    }
}

class MyCallable implements Callable<Integer> {
    private final int number;

    public MyCallable(int number) {
        this.number = number;
    }

    @Override
    public Integer call() throws Exception {
        System.out.println("任务 " + number + " 正在执行，线程：" + Thread.currentThread().getName());
        Thread.sleep(1000); // 模拟任务执行时间
        return number;
    }
}